<?php


namespace addons\Minerva\api\modules\v1\controllers;

use common\enums\WhetherEnum;
use common\widgets\jstree\JsTree;
use Yii;
use api\controllers\OnAuthController;
use common\enums\AppEnum;
use common\enums\StatusEnum;
use common\models\rbac\AuthItem;
use common\traits\AuthItemTrait;
use yii\data\ActiveDataProvider;
use yii\helpers\Json;

/**
 * Class AuthItemController
 * @package backend\modules\base\controllers
 * @author jianyan74 <751393839@qq.com>
 */
class AuthItemController extends OnAuthController
{
    use AuthItemTrait;

    public $name;
    /**
     * @var string
     */
    public $theme = 'default';
    /**
     * 默认数据
     *
     * @var array
     */
    public $defaultData = [];
    /**
     * 选择的ID
     *
     * @var array
     */
    public $selectIds = [];
    /**
     * 过滤掉的ID
     *
     * @var array
     */
    protected $filtrationId = [];


    /**
     * @var AuthItem
     */
    public $modelClass = AuthItem::class;

    /**
     * 默认应用
     *
     * @var string
     */
    public $appId = AppEnum::BACKEND;

    /**
     * 渲染视图前缀
     *
     * @var string
     */
    public $viewPrefix = '@backend/modules/base/views/auth-item/';

    public function actionIndex(){
        $allAuth = Yii::$app->services->rbacAuthItem->findAll($this->appId);
        $list = list($defaultFormAuth, $defaultCheckIds, $addonsFormAuth, $addonsCheckIds) = Yii::$app->services->rbacAuthRole->getJsTreeData('', $allAuth);

        $list = Yii::$app->services->rbacAuthRole->getDropDownForEdit($this->appId, '');
        $list = new ActiveDataProvider([
            'query' => AuthItem::find()
                ->where(['app_id' => $this->appId])
                ->andWhere(['>=', 'status', StatusEnum::DISABLED])
//                ->andFilterWhere(['merchant_id' => Yii::$app->services->merchant->getId()])
//                ->andFilterWhere(Yii::$app->services->rbacAuthRole->roleCondition($this->sourceAuthChild))
                ->orderBy('sort asc, created_at asc')
                ->asArray(),
            'pagination' => false
        ]);
        return $list;
        $tree = new JsTree();
        $tree->defaultData = $defaultFormAuth;
        $tree->selectIds = $defaultCheckIds;
        $res = $tree->run();
        return $res;
    }

    public function actionList()
    {
        $member_id = Yii::$app->user->identity->member_id;
        $role = Yii::$app->services->rbacAuthAssignment->findByUserIdAndAppId($member_id,$this->appId);
        $allAuth = Yii::$app->services->rbacAuthItem->findAll($this->appId);
        $list = list($defaultFormAuth, $defaultCheckIds, $addonsFormAuth, $addonsCheckIds) = Yii::$app->services->rbacAuthRole->getJsTreeData($role['role_id'], $allAuth);
        $this->defaultData = $addonsFormAuth;
        $this->selectIds = $addonsCheckIds;
        $defaultData = $this->defaultData;
        $selectIds = $this->selectIds;
        list($auth,$ids) = $this->getJsTreeData($role['role_id'],$allAuth);
        $auths =self::itemsMerge($auth);
        $auths = self::isChecked($auths,$ids);
        return $auths;
    }

    public function actionRun()
    {
        $id = Yii::$app->request->get('id', null);
        $allAuth = Yii::$app->services->rbacAuthItem->findAll($this->appId);
        $list = list($defaultFormAuth, $defaultCheckIds, $addonsFormAuth, $addonsCheckIds) = Yii::$app->services->rbacAuthRole->getJsTreeData($id, $allAuth);
        $this->defaultData = $addonsFormAuth;
        $this->selectIds = $defaultCheckIds;
        $defaultData = $this->defaultData;
        $selectIds = $this->selectIds;
        list($auth,$ids) = $this->getJsTreeData($id,$allAuth);
        $auths =self::itemsMerge($auth);
        $auths = self::isChecked($auths,$ids);
        return $auths;
    }

    //授权
    public function actionEmpower(){
        $member_id = Yii::$app->user->identity->member_id;
        $role = Yii::$app->services->rbacAuthAssignment->findByUserIdAndAppId($member_id,$this->appId);
        $data = Yii::$app->request->post();
        $ids = explode(',', $data['ids']);
        Yii::$app->services->rbacAuthItemChild->accredit($role['role_id'], $ids ?? [], WhetherEnum::ENABLED, $this->appId);
        return 'success';
    }

    public static function isChecked($auths,$ids){
        $arr = [];
        foreach ($auths as $key => $val) {
            if (in_array($val['id'], $ids)) {
                $val['is_checked'] = true;
                if (!empty($val['-'])) {
                    $val['-'] = self::isChecked($val['-'],$ids);
                }
            }
            $arr[] = $val;
        }
        return $arr;
    }

    /**
     * 过滤
     *
     * @param $data
     */
    public function filtration($data)
    {
        foreach ($data as $datum) {
            if (!empty($datum['-'])) {
                $this->filtration($datum['-']);

                if (in_array($datum['id'], $this->selectIds)) {
                    $ids = array_column($datum['-'], 'id');
                    $selectChildIds = array_intersect($this->selectIds, $ids);
                    if (count($selectChildIds) != count($ids)) {
                        $this->filtrationId[] = $datum['id'];
                    }
                }
            }
        }
//        return $data;
    }

    /**
     * 传递一个子分类ID返回所有的父级分类
     *
     * @param array $items
     * @param $id
     * @return array
     */
    public static function getParents(array $items, $id)
    {
        $arr = [];
        foreach ($items as $v) {
            if (is_numeric($id)) {
                if ($v['id'] == $id) {
                    $arr[] = $v;
                    $arr = array_merge(self::getParents($items, $v['pid']), $arr);
                }
            }
        }

        return $arr;
    }

    /**
     * 递归
     *
     * @param array $items
     * @param int $pid
     * @param string $idField
     * @param string $pidField
     * @param string $child
     * @return array
     */
    protected static function itemsMerge(array $items, $pid = 0)
    {
        $arr = [];
        foreach ($items as $v) {
            if (is_numeric($pid)) {
                if ($v['pid'] == $pid) {
                    $v['-'] = self::itemsMerge($items, $v['id']);
                    $arr[] = $v;
                }
            }
        }

        return $arr;
    }

    /**
     * 获取编辑的数据
     *
     * @param int $role_id
     * @param array $allAuth
     * @return array
     *
     */
    public function getJsTreeData($role_id, array $allAuth)
    {
        // 当前角色已有的权限
        $auth = Yii::$app->services->rbacAuthItemChild->findItemByRoleId($role_id);
        // return $auth;
        $addonName = $formAuth = $checkIds = $addonFormAuth = $addonsCheckIds = [];

        // 区分默认和插件权限
        foreach ($allAuth as $item) {
            if ($item['is_addon'] == WhetherEnum::ENABLED && $item['addons_name'] == 'Minerva') {
                $formAuth[] = $item;
                $item['is_checked'] = false;
                $addonFormAuth[] = $item;
                $addonName[$item['addons_name']] = $item['addons_name'];
            }
        }

        // 区分默认和插件权限ID
        foreach ($auth as $value) {
            if (empty($value)) {
                continue;
            }
            if ($value['is_addon'] == WhetherEnum::ENABLED && $value['addons_name'] == 'Minerva') {
                $addonsCheckIds[] = $value['id'];
            }
        }
        return [$addonFormAuth, $addonsCheckIds];
    }
}